import json
from enum import Enum

import requests
from tools import logger
import config


class ReplyType(Enum):
    TEXT = 1  # 文本
    VOICE = 2  # 音频文件
    IMAGE = 3  # 图片文件
    IMAGE_URL = 4  # 图片URL
    VIDEO_URL = 5  # 视频URL
    FILE = 6  # 文件
    CARD = 7  # 微信名片，仅支持ntchat
    INVITE_ROOM = 8  # 邀请好友进群
    INFO = 9
    ERROR = 10
    TEXT_ = 11  # 强制文本
    VIDEO = 12
    MINIAPP = 13  # 小程序
    SKIP = 14  # 跳过

    def __str__(self):
        return self.name


class Reply:
    def __init__(self, type: ReplyType = None, content=None):
        self.type = type
        self.content = content

    def __str__(self):
        return "Reply(type={}, content={})".format(self.type, self.content)


def get_reply_from_backend(context):
    url = f"{config.SERVER_HOST}:{config.SERVER_PORT}/chat"
    logger.info(f"[reply_channel]Server URL = f{url}")
    headers = {'Content-Type': 'application/json'}
    data = json.dumps(context.to_dict(), ensure_ascii=False, indent=4)
    logger.info(f"[reply_channel] Send request to server: {data}")
    try:
        response = requests.post(url, data=data, headers=headers)
        response.raise_for_status()
        # logger.info(f"[reply_channel] Get response from server: {response.json()}")
        resData = response.json()[0]
        # desire_rtype = resData['desire_rtype']
        if response.status_code == 200:
            if resData['type'] == 'text':
                return Reply(ReplyType.TEXT, resData['content'])
            if resData['type'] == 'file':
                return Reply(ReplyType.FILE, resData['content'])
            if resData['type'] == 'skip':
                return Reply(ReplyType.SKIP)
            if resData['type'] == 'error':
                return Reply(ReplyType.ERROR, resData['content'])
        else:
            logger.error(f"[reply_channel] Response not equals 200 from server: {response.json()}")
            return Reply(ReplyType.ERROR, f"额，额，我不知道发生了什么，我去叫下我爹...|||我出问题啦！快看看：\n{response.json()}")
    except requests.exceptions.HTTPError as e:
        logger.error(f"[reply_channel] HTTPError: {e}")
        return Reply(ReplyType.ERROR, f"额，我正在睡觉, 别吵我...|||我出问题啦！快看看：\n 大概率是服务器没开：{e}")
    except requests.exceptions.RequestException as e:
        logger.error(f"[reply_channel] RequestException: {e}")
        return Reply(ReplyType.ERROR, f"额，我正在睡觉, 别吵我...|||我出问题啦！快看看：\n{e}")
    except Exception as e:
        return Reply(ReplyType.ERROR, f"额，我正在睡觉, 别吵我...|||我出问题啦！快看看：\n{e}")
